
import printf from 'printf';
import { LANGUAGE } from '../constant';

/**
 * 缓存资源信息，防止每次都去require文件
 */
let cacheStorage: { [index: string]: ResourceMap } = {};

export const L = {
    ARTICLE: 'ARTICLE',
    ALBUM: 'ALBUM',
    PICTURE: 'PICTURE',
    CATEGORY: 'CATEGORY',
    SHORTURL: 'SHORTURL',
    TAG: 'TAG',
    NOT_FOUND: 'NOT_FOUND',
    SYSTEM_ERROR: 'SYSTEM_ERROR',
    PARAM_INVALID: 'PARAM_INVALID'
}

export interface ResourceMap { 
    ARTICLE?: string;
    ALBUM?: string;
    PICTURE?: string;
    CATEGORY?: string;
    SHORTURL?: string;
    TAG?: string;
    USER?: string;
    NOT_FOUND?: string,
    SYSTEM_ERROR?: string,
    PARAM_INVALID?: string,
    [index: string]: any;
}

/**
 * 
 * @param {string} lang 语言类型
 * @param {string} key 关键字
 * @param {Array<string|number|boolean>} args 
 */
export function getValue(lang: string, key: keyof ResourceMap, ...args: (string| number| boolean)[]) { 
    let defaultLang = LANGUAGE;
    let resources = getResource(lang);
    let defaultResources = getResource(defaultLang);

    if (!defaultResources) { 
        throw new Error(`默认语言${defaultLang}文件不存在`)
    }
    resources = Object.assign(defaultResources, resources);
    return printf(resources[key], args);
}

export function getResource(lang: string) { 
    let resources = cacheStorage[lang];
    if (!resources) {
        try {
            resources = require(`./${lang}`);
        } catch (err) {
            resources = {};
        }
        cacheStorage[lang] = resources;
    }
    return resources;
}